package com.lijin.workshop.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

public final class FileUtil {

	private static final Logger logger = Logger.getLogger(FileUtil.class);
	
	/**
	 * 读取文件，并逐行进行处理
	 * @param filePath 文件路径
	 * @param charset 读取文件的编码，如果未指定，则默认用GBK
	 * @param handler 每行信息的处理类
	 */
	public static void readFileByLine(String filePath, String charset, FileLineHandler handler) {
		logger.info("开始读取文件:" + filePath);
		File f = new File(filePath);
		if (f.exists()) {
			InputStream in = null;
			BufferedReader reader = null;
			try {
				in = new FileInputStream(f);
				// 默认用GBK格式读取文件
				reader = new BufferedReader(new InputStreamReader(in, StringUtil.isBlank(charset)?"GBK":charset.trim()));
				int lineNo = 0;
				while (reader.ready()) {
					String line = reader.readLine();
					lineNo ++;
					try {
						handler.handleLine(line);
					} catch (Exception e) {
						logger.info("行数据处理出错[" + lineNo + "]:" + line, e);
					}
				}
			} catch (Exception e) {
				logger.error("读取文件出错:" + filePath, e);
			} finally {
				IOUtil.close(reader);
				IOUtil.close(in);
			}
		} else {
			logger.info("文件不存在:" + filePath);
		}
	}
	
	public static void writeFileByLine(File f, List<String> contents, String charset) {
		if (charset == null || "".equals(charset.trim())) {
			charset = "UTF-8";
		}
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), charset));
			for (String line : contents) {
				writer.write(line);
				writer.newLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				IOUtil.close(writer);
			}
		}
	}
	
	public static void main(String[] args) {
		String file = "D:\\exist_acq.txt";
		final Set<String> existAcqs = new HashSet<String>();
		FileUtil.readFileByLine(file, "UTF-8", new FileLineHandler() {
			@Override
			public void handleLine(String line) {
				if (!StringUtil.isBlank(line)) {
					existAcqs.add(StringUtil.trim(line));
				}
			}
		});
		System.out.println("已存在的机构数:" + existAcqs.size());
		
		file = "D:\\acq_cds.txt";
		final Map<String, String> acqMap = new HashMap<String, String>();
		FileUtil.readFileByLine(file, "GBK", new FileLineHandler() {
			@Override
			public void handleLine(String line) {
				String cd = line.split("[|]")[1];
				String name = line.split("[|]")[0];
				if (existAcqs.contains(cd)) {
					System.out.println("已存在:" + cd);
				} else {
					acqMap.put(cd, name);
				}
			}
		});
		System.out.println("待保存的机构:" + acqMap.size());
		
		String targFile = "D:\\acq_batch_add.sql";
		BufferedWriter writer = null;
		String tmpl = "insert into TBL_UPONL_ACQ_INF (MCHNT_ID, MCHNT_CD, ACQ_INS_ID_CD, MCHNT_TP, MCHNT_SUB_TP, YEAR_TURNOVER_AT, ONLINE_TURNOVER_AT, MCHNT_NM, MCHNT_COMPANY, MCHNT_TELEPHONE, MCHNT_EMAIL, COMMERCIAL_INSTRUMENT, CORPORATION_REPRESENTIVE, CONCACTOR, ADDRESS, POSTCODE, WEB_SITE, CONTRACT, ICP_ID, SIGNUP_TIME, EXPIRE_TIME, COUNTRY_CD, AREA_CD, PAY_PWD, QUESTION1, QUESTION2, QUESTION3, ANSWER1, ANSWER2, ANSWER3, SECURE_EMAIL, SECURE_KEY, CTRL_RULE1, CTRL_RULE2, CTRL_RULE3, MCHNT_POLICY, STATUS, REC_CRT_TS, REC_UPD_TS, TRANS_IP, REC_ST, COMMENTS, MCHNT_CLASS, CONN_MD, MCHNT_EN_NM, COMPANY_EN_ADDR, COUNTRY_ABBR, SETTLE_CURR_CD, CTRL_RULE4, CTRL_RULE5, CTRL_RULE6, CHANNEL) values (nextval for SEQ_UPONL_MCHNT_ID, '               ', 'real_acq_cd', '    ', '    ', 0, 0, 'real_acq_name', '', '', '', '', '                                                                ', '', '', '', 'null', '', '', current timestamp, current timestamp, '142', '    ', '', '', '', '', '', '                                ', '', '', '1724586934552771', 2103, 0, 0, 1005, ' ', current timestamp, current timestamp, '                                       ', '1', '', '    ', '0 ', '', '', '   ', '156', '00000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 1);";
		try {
			writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(targFile), "GBK"));
			for (String cd : acqMap.keySet()) {
				String str = tmpl.replaceAll("real_acq_cd", cd).replaceAll("real_acq_name", acqMap.get(cd));
				writer.write(str);
				writer.newLine();
			}
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				IOUtil.close(writer);
			}
		}
	}
}
